package com.lzj.server.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;

/**
 * 创建或者更新时间字段自动填充
 */
@Configuration
@Slf4j
public class DateTimeFieldFillConfig implements MetaObjectHandler {

    // 创建和更新时间的方法 (mini策略模式)
    private void setCurrentTimestamp(MetaObject metaObject, String fieldName) {
        try {
            this.setFieldValByName(fieldName,  LocalDateTime.now(), metaObject);
        } catch (Exception e) {
            // 记录异常，处理错误情况
            log.error("设置当前时间失败: {}", e.getMessage());
        }
    }

    // 创建时间的方法
    @Override
    public void insertFill(MetaObject metaObject) {
        setCurrentTimestamp(metaObject, "createTime");
        setCurrentTimestamp(metaObject, "updateTime");
    }

    // 更新时间的方法
    @Override
    public void updateFill(MetaObject metaObject) {
        setCurrentTimestamp(metaObject, "updateTime");
    }
}
